import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings

# 忽略警告
warnings.filterwarnings("ignore")
# 显示中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 用户行为分析
data = pd.read_csv(r'..\taobao\data\taobao_1.csv')
# print(data.head())
# print(data.shape)
#  以日为维度进行拆解行为
pv_date_type = pd.pivot_table(data, index='日期'
                              , columns='行为'
                              , values='用户名'
                              , aggfunc=np.size)
pv_date_type.columns = ['点击', '收藏', '加入购物车', '支付']

print(pv_date_type)

plt.figure(figsize=(16, 10))
sns.pointplot(data=pv_date_type[['点击', '收藏', '加入购物车', '支付']])
plt.savefig('./picture/日期客户转换趋势.svg')
plt.show()

plt.figure(figsize=(26, 10))
sns.lineplot(data=pv_date_type[['收藏', '加入购物车', '支付']])
plt.savefig('./picture/日期客户转换趋势_1.svg')
plt.savefig("", dpi=300)

plt.show()

#  以小时为维度进行拆解行为
pv_date_type = pd.pivot_table(data, index='小时'
                              , columns='行为'
                              , values='用户名'
                              , aggfunc=np.size)
pv_date_type.columns = ['点击', '收藏', '加入购物车', '支付']

print(pv_date_type.head())

plt.figure(figsize=(16, 10))
sns.pointplot(data=pv_date_type[['点击', '收藏', '加入购物车', '支付']])
plt.show()

plt.figure(figsize=(16, 10))
sns.lineplot(data=pv_date_type[['点击', '收藏', '加入购物车', '支付']])
plt.xticks(range(0, 24), pv_date_type.index)
plt.savefig('./picture/日内客户转换趋势.svg')
plt.show()

plt.figure(figsize=(16, 10))
sns.lineplot(data=pv_date_type[['收藏', '加入购物车', '支付']])
plt.xticks(range(0, 24), pv_date_type.index)
plt.savefig('./picture/日内客户转换趋势_1.svg')
plt.show()

# 行为转化漏斗模型
data_count = data.groupby('行为').count()['用户名'].reset_index().rename(columns={'用户名': '人数'})
print(data_count)

# 求单一转化率
data_count['人数'] = data_count['人数'].astype('int')
num = list(data_count['人数'])
k = [1.00]
for i in range(3):
    num_1 = num[i]
    num_2 = num[i + 1]
    num_3 = num_2 / num_1
    k.append(num_3)
print(k)

single_convs = [round(x * 100, 2) for x in k]
data_count['单一转换率'] = single_convs

# 总体转换率
all_convs = data_count['人数'] / data_count['人数'][0]
all_convs = [round(x * 100, 2) for x in all_convs]
data_count['总体转换率'] = all_convs
print(data_count)
data_count.to_csv(r'..\taobao\data\user_transform.csv', encoding="utf_8_sig")


